<?php

function getExchangeData($company) {
    $stockData = array();
    $url = 'http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=' . $company . '&callback=YAHOO.Finance.SymbolSuggest.ssCallback';

    // get the data and convert it into json format
    $result = preg_replace('/.+?({.+}).+/', '$1', file_get_contents($url));
    $resultJson = json_decode($result);
    
    // save just the results
    $data = $resultJson->ResultSet->Result;

    if ($data) {
        
        $stockSymbol = "";
        $gotSymbol  = false;

        foreach($data as $company) {
            if (!$gotSymbol && $company->exchDisp == "Frankfurt") {
                $stockSymbol = $company->symbol;
                $gotSymbol  = true;
            }
        }

        if ($gotSymbol) {
            /* Statement erzeugen */
            $statment = 'select Name, LastTradePriceOnly from yahoo.finance.quotes where symbol in ("'.$stockSymbol.'") | sort(field="LastTradePriceOnly", descending="true")';

            /* Request-URL zusammensetzen */
            $base = 'http://query.yahooapis.com/v1/public/yql?';
            $config = '&format=json&env=http://datatables.org/alltables.env&callback=';
            $url = $base.'q='.urlencode($statment).$config;

            /* Response einlesen */
            $result = file_get_contents($url);

            if ($result) {
                $resultJson = json_decode($result);
                $data = $resultJson->query;

                if (!$data->results) {
                    $stockData["status"] = 404;
                } else {
                    $stockData["status"] = 200;
                    $stockData["name"]  = $data->results->quote->Name;
                    $stockData["actualprice"] = $data->results->quote->LastTradePriceOnly;
                //    $value = $price * $countStocks;
                }
            }
        }
    } else {
        $stockData["status"] = '404';
    }

    return $stockData;
}